# utils/email_sender.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import config.config


def send_email(subject, body, attachment_path=None):
    # 邮箱配置
    smtp_server = config.config.MAIL_SERVER
    smtp_port = config.config.MAIL_PORT
    sender_email = config.config.MAIL_USERNAME
    sender_password = config.config.MAIL_PASSWORD
    recipient_emails = config.config.MAIL_DEFAULT_SENDER

    # 创建邮件内容
    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = ", ".join(recipient_emails)
    msg["Subject"] = subject

    # 添加正文
    msg.attach(MIMEText(body, "plain"))

    # 添加附件
    if attachment_path:
        with open(attachment_path, "rb") as attachment:
            part = MIMEBase("application", "octet-stream")
            part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header(
            "Content-Disposition",
            f"attachment; filename={attachment_path.split('/')[-1]}",
        )
        msg.attach(part)

    # 发送邮件
    try:
        with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
            server.login(sender_email, sender_password)
            server.sendmail(sender_email, recipient_emails, msg.as_string())
        print("Email sent successfully!")
    except Exception as e:
        print(f"Failed to send email: {e}")


# 示例：发送邮件
if __name__ == "__main__":
    send_email(
        subject="测试报告",
        body="请查收附件中的测试报告。",
        attachment_path=config.config.REPORTS_HTML_PATH,
    )
